<template>
  <div>
    <!-- 顶部 -->
    <el-card>
      <el-row>
        <el-col :span="7" class="top_input">
          <label>工号：</label>
          <el-input
            v-model="searchModel.driverId"
            clearable
            placeholder="请输入工号"
          >
          </el-input>
        </el-col>
      </el-row>

      <div style="margin-left: 5px">
        <el-button type="primary" plain size="small" @click="getDriversList()"
          >搜索</el-button
        >

        <el-button
          type="primary"
          plain
          size="small"
          @click="openDriverDig(null)"
          >添加司机</el-button
        >
      </div>
    </el-card>

    <!-- 用户展示区域 -->
    <el-card class="box-card">
      <el-table :data="driversList" style="width: 100%" v-loading="loadling">
        <el-table-column prop="driverId" label="工号" width="260">
        </el-table-column>

        <el-table-column prop="driverLicense" label="驾驶证号码" width="180">
        </el-table-column>
        <el-table-column prop="licenseType" label="驾驶证类型">
        </el-table-column>
        <el-table-column prop="licenseExpiry" label="驾驶证到期时间">
        </el-table-column>
        <el-table-column prop="rating" label="评分"> </el-table-column>
        <el-table-column prop="drivingExperience" label="驾龄">
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <!-- available-可用，on_duty-出勤中，off_duty-下班，on_leave-休假 -->
            <el-tag
              type="success"
              effect="dark"
              v-if="scope.row.status == 'available'"
              >可用</el-tag
            >
            <el-tag
              type="warning"
              effect="dark"
              v-if="scope.row.status == 'on_duty'"
              >出勤中</el-tag
            >
            <el-tag
              type="danger"
              effect="dark"
              v-if="scope.row.status == 'off_duty'"
              >下班</el-tag
            >
            <el-tag
              type="info"
              effect="dark"
              v-if="scope.row.status == 'on_leave'"
              >休假</el-tag
            >
          </template>
        </el-table-column>

        <el-table-column prop="notes" label="备注"> </el-table-column>
        <el-table-column width="220" label="操作">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="openDriverDig(scope.row.driverId)"
              >编辑</el-button
            >
            <el-button
              type="text"
              size="small"
              @click="openAssignCar(scope.row.driverId)"
              >分配汽车</el-button
            >
            <el-button
              type="text"
              size="small"
              style="color: red"
              @click="del(scope.row.driverId)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-pagination
      @current-change="handleCurrentChange"
      :current-page="searchModel.pageNo"
      :page-size="searchModel.pageSize"
      layout="total,  prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

    <!-- 司机编辑对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <el-form ref="driversForm" :rules="rules" :model="driversForm">
        <el-form-item label="用户名称" label-width="110px" prop="userId">
          <el-select
            v-model="driversForm.userId"
            filterable
            placeholder="请选择用户名称"
          >
            <el-option
              v-for="item in UserOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="驾驶证号码"
          label-width="110px"
          prop="driverLicense"
        >
          <el-input
            v-model="driversForm.driverLicense"
            placeholder="请输入驾驶证号码"
          ></el-input>
        </el-form-item>
        <el-form-item label="驾驶证类型" label-width="110px" prop="licenseType">
          <el-select
            v-model="driversForm.licenseType"
            placeholder="请选择驾驶证类型"
          >
            <el-option
              v-for="item in licenseTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="驾驶证到期日"
          label-width="110px"
          prop="licenseExpiry"
        >
          <el-date-picker
            v-model="driversForm.licenseExpiry"
            type="date"
            placeholder="选择驾驶证到期日"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item
          label="驾龄(年)"
          label-width="110px"
          prop="drivingExperience"
        >
          <el-input-number
            v-model="driversForm.drivingExperience"
            :min="0"
            :max="100"
            placeholder="驾龄(年)"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="司机评分" label-width="110px" prop="rating">
          <el-input-number
            v-model="driversForm.rating"
            :min="0"
            :step="0.1"
            :precision="2"
            :max="5"
            placeholder="司机评分"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="司机状态" label-width="110px" prop="status">
          <el-select v-model="driversForm.status" placeholder="请选择司机状态">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="司机备注信息" label-width="110px" porp="notes">
          <el-input
            v-model="driversForm.notes"
            type="textarea"
            :rows="2"
            placeholder="请输入司机备注信息"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="saveDriver()">确定</el-button>
          <el-button @click="close()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 分配汽车 -->
    <el-dialog
      title="分配汽车"
      :visible.sync="dialogVisibleAssignCar"
      width="30%"
      :before-close="handleCloseAssignCar"
    >
      <el-form
        ref="assignCarForm"
        :rules="CarRules"
        :model="assignCarForm"
        label-width="80px"
      >
        <el-form-item label="车辆" prop="carId">
          <el-select
            v-model="assignCarForm.carId"
            filterable
            placeholder="请选择车辆"
          >
            <el-option
              v-for="item in carOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="assignCar()">确定分配</el-button>
          <el-button @click="closeAssignCar()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<style>
.top_input {
  margin: 4px;
}
</style>

<script>
import driversApi from "@/api/drivers";
import userApi from "@/api/userApi";
import carApi from "@/api/car";
export default {
  data() {
    return {
      loadling: false,

      searchModel: {
        pageNo: 1,
        pageSize: 10,
      },
      driversList: [],
      total: 0,

      // 司机编辑对话框
      title: "测试",
      dialogVisible: false,
      driversForm: {},

      // 驾驶证类型
      licenseTypeOptions: [
        {
          value: "C1",
          label: "小型汽车-C1",
        },
        {
          value: "C2",
          label: "小型自动挡汽车-C2",
        },
        {
          value: "C3",
          label: "低速载货汽车-C3",
        },
        {
          value: "C4",
          label: "三轮汽车-C4",
        },
        {
          value: "C5",
          label: "残疾人专用小型自动挡载客汽车-C5",
        },
        {
          value: "B1",
          label: "中型客车-B1",
        },
        {
          value: "B2",
          label: "大型货车-B2",
        },
        {
          value: "A1",
          label: "大型客车-A1",
        },
        {
          value: "A2",
          label: "牵引车-A3",
        },
        {
          value: "A3",
          label: "城市公交车-A3",
        },
      ],

      // 司机状态
      statusOptions: [
        //available-可用，on_duty-出勤中，off_duty-下班，on_leave-休假
        {
          value: "available",
          label: "可用",
        },
        {
          value: "on_duty",
          label: "出勤中",
        },
        {
          value: "off_duty",
          label: "下班",
        },
        {
          value: "on_leave",
          label: "休假",
        },
      ],

      UserOptions: [],

      // 规则
      rules: {
        userId: [{ required: true, message: "请选择用户", trigger: "change" }],
        driverLicense: [
          { required: true, message: "请输入驾驶证号", trigger: "blur" },
          {
            min: 5,
            max: 64,
            message: "长度在 3 到 64 个字符",
            trigger: "blur",
          },
        ],
        licenseType: [
          { required: true, message: "请选择驾驶证类型", trigger: "change" },
        ],

        status: [
          { required: true, message: "请选择司机状态", trigger: "change" },
        ],
        licenseExpiry: [
          {
            type: "date",
            required: true,
            message: "请选择驾驶证到期时间",
            trigger: "change",
          },
        ],

        drivingExperience: [
          { required: true, message: "驾龄不能为空" },
          { type: "number", message: "驾龄必须为数字值" },
        ],

        notes: [{ max: 255, message: "长度要小于255个字符", trigger: "blur" }],
      },

      // 分配汽车对话框
      dialogVisibleAssignCar: false,
      assignCarForm: {
        carId: "",
        driverId: "",
      },
      carOptions: [],
      CarRules: {
        carId: [
          {
            required: true,
            message: "请选择车辆",
            trigger: "change",
          },
        ],
      },
    };
  },
  methods: {
    handleClose() {
      this.$confirm("确认关闭？")
        .then((_) => {
          this.close();
          done();
        })
        .catch((_) => {});
    },

    close() {
      this.driversForm = {};
      this.dialogVisible = false;
      this.$refs["driversForm"].resetFields();
    },

    getDriversList() {
      this.loadling = true;
      driversApi
        .getDriversList(this.searchModel)
        .then((response) => {
          this.driversList = response.data.rows;
          this.total = response.data.total;
        })
        .finally(() => {
          this.loadling = false;
        });
    },

    closeAssignCar() {
      this.dialogVisibleAssignCar = false;
      this.assignCarForm = {};
      this.$refs.assignCarForm.resetFields();
    },

    handleCloseAssignCar() {
      this.$confirm("确认关闭？")
        .then((_) => {
          this.closeAssignCar();
          done();
        })
        .catch((_) => {});
    },

    closeAssignCar() {
      this.dialogVisibleAssignCar = false;
      this.assignCarForm = {};
      this.$refs.assignCarForm.resetFields();
    },

    handleCurrentChange(val) {
      this.searchModel.pageNo = val;
      this.getDriversList();
    },

    // 获取用户选择器
    getUserOptions() {
      this.loadling = true;
      userApi
        .getUserOperations()
        .then((response) => {
          this.UserOptions = response.data;
        })
        .finally(() => {
          this.loadling = false;
        });
    },

    // 打开对话框
    openDriverDig(id) {
      this.getUserOptions();
      if (id !== null) {
        this.title = "修改司机信息";

        // 回显数据
        this.loadling = true;
        driversApi
          .getDriversById(id)
          .then((response) => {
            this.driversForm = response.data;
            this.driversForm.licenseExpiry = new Date(
              this.driversForm.licenseExpiry
            );
          })
          .finally(() => {
            this.loadling = false;
          });
      } else {
        this.title = "新增司机信息";
      }
      this.dialogVisible = true;
    },

    saveDriver() {
      this.$refs["driversForm"].validate((valid) => {
        if (valid) {
          this.loadling = true;
          driversApi
            .saveDrivers(this.driversForm)
            .then((response) => {
              this.$message({
                message: response.message,
                type: "success",
              });
              this.close();
              this.getDriversList();
            })
            .finally(() => {
              this.loadling = false;
            });
        } else {
          return false;
        }
      });
    },

    del(id) {
      this.$confirm("此操作将永久删除该司机, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.loadling = true;
          driversApi
            .deleteByid(id)
            .then((response) => {
              this.$message({
                type: "success",
                message: response.message,
              });
              this.getDriversList();
            })
            .finally(() => {
              this.loadling = false;
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    getcarOptions() {
      this.loadling = true;
      carApi
        .getCarOptions()
        .then((response) => {
          this.carOptions = response.data.data;
        })
        .finally(() => {
          this.loadling = false;
        });
    },

    // 打开分配汽车对话框
    openAssignCar(id) {
      console.log(this.assignCarForm);

      // 回显数据
      driversApi.getDriversById(id).then((res) => {
        this.getcarOptions();

        if (res.data.currentVehicleId != null) {
          this.assignCarForm.carId = res.data.currentVehicleId;
        }
        this.assignCarForm.driverId = id;

        this.dialogVisibleAssignCar = true;
      });
    },

    assignCar() {
      this.$refs.assignCarForm.validate((valid) => {
        if (valid) {
          this.loadling = true;
          const driverId = this.assignCarForm.driverId;
          const carId = this.assignCarForm.carId;
          driversApi
            .assignCar(driverId, carId)
            .then((response) => {
              this.$message({
                message: response.message,
                type: "success",
              });
              this.closeAssignCar();
              this.getDriversList();
            })
            .finally(() => {
              this.loadling = false;
            });
        } else {
          return false;
        }
      });
    },
  },
  computed: {
    headers() {
      return {};
    },
  },

  created() {
    this.getDriversList();
  },
};
</script>
